package com.bml.architect.framework.protocol.dubbo;

import com.alibaba.fastjson.JSONObject;
import com.bml.architect.framework.Invocation;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;


public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable<String> {

    private ChannelHandlerContext context = null;

    private Invocation invocation;

    private String result = null;

    @Override
    public synchronized  void channelActive(ChannelHandlerContext ctx) throws Exception {

        this.context = ctx;
    }

    @Override
    public synchronized  void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();
    }



    @Override
    public synchronized  String call() throws Exception {
        String s = JSONObject.toJSONString(invocation);
        context.writeAndFlush(s);
        wait();
        return result;

    }

    public void setInvocation(Invocation invocation) {
        this.invocation = invocation;
    }
}
